//
//  FeedCell.m
//  collection
//
//  Created by 张靖 on 1/7/12.
//  Copyright (c) 2012 Tsinghua University. All rights reserved.
//

#import "FeedCell.h"
#import "Utility.h"
#import "ViewPictureController.h"

@interface FeedCell()

- (void)createCtrls;
- (void)onClickFavouriteMask:(id)sender;
- (void)onClickImage:(UIGestureRecognizer*)gestureRecognizer;

@end

@implementation FeedCell

@synthesize avatarImageView = _avatarImageView;
@synthesize nicknameLabel   = _nicknameLabel;
@synthesize favouriteButton = _favouriteButton;
@synthesize timestampLabel  = _timestampLabel;
@synthesize noteLabel       = _noteLabel;
@synthesize imageAreaView   = _imageAreaView;
@synthesize sourceAreaView  = _sourceAreaView;
@synthesize descAreaView    = _descAreaView;

- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier {
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self != nil) {
        [self createCtrls];
    }
    
    UIView* bgView = [[UIView alloc] initWithFrame:self.frame];
    bgView.backgroundColor = [UIColor colorWithRed:229.0 / 255.0 green:229.0 / 255.0 blue:229.0 / 255.0 alpha:1];
    self.selectedBackgroundView = bgView;
    [bgView release];
    
    return self;
}

- (id)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    
    return self;
}

- (void)dealloc {
/*    
    self.avatarImageView    = nil;
    self.nicknameLabel      = nil;
    self.timestampLabel     = nil;
    self.noteLabel          = nil;
    self.imageAreaView      = nil;
    self.sourceAreaView     = nil;
    self.descAreaView       = nil;
*/    
    [super dealloc];
}

#pragma mark - Public methods

#define XEDGEMARGIN     9       // Margin from the cell edge in x
#define YEDGEMARGIN     9       // Margin from the cell edge in y
#define XCTRLMARGIN     8       // Margin between controls in x
#define YCTRLMARGIN     8       // Margin between controls in y

- (void)createCtrls {
/*    
    // Avatar
    UIImageView* avatarImageView = [[UIImageView alloc] initWithFrame:CGRectZero];
    self.avatarImageView = avatarImageView;
    [avatarImageView release];
    
    // Nickname
    UILabel* nicknameLabel = [[UILabel alloc] initWithFrame:CGRectZero];
    self.nicknameLabel = nicknameLabel;
    [nicknameLabel release];
    
    // Time stamp
    UILabel* timestampLabel = [[UILabel alloc] initWithFrame:CGRectZero];
    self.timestampLabel = timestampLabel;
    [timestampLabel release];
    
    // Note
    UILabel* noteLabel = [[UILabel alloc] initWithFrame:CGRectZero];
    self.noteLabel = noteLabel;
    [noteLabel release];
*/   
    
}

- (void)onClickFavouriteMask:(id)sender {
    
    UIButton* maskButton = (UIButton*)sender;
    
    CGRect oldFrame = maskButton.frame;
    
    const int sideLen = oldFrame.size.width * 2.5;
    CGRect frame1 = CGRectMake(oldFrame.origin.x + oldFrame.size.width / 2 - sideLen / 2, oldFrame.origin.y + oldFrame.size.height / 2 - sideLen / 3, sideLen, sideLen);
    UIImageView* imageView = [[UIImageView alloc] initWithFrame:oldFrame];
    imageView.contentMode = UIViewContentModeScaleToFill;

    if (maskButton.selected) {
        imageView.image = [UIImage imageNamed:@"ico_heart_off"];
    }
    else {
        imageView.image = [UIImage imageNamed:@"ico_heart_on"];
    }

    [self.contentView addSubview:imageView];
    [imageView release];
    
    maskButton.selected = !maskButton.selected;
    [UIView animateWithDuration:0.6f
                     animations:^{
                         imageView.alpha = 0;
                         imageView.frame = frame1;
                     } 
                     completion:^(BOOL finished){
                         
                         [imageView removeFromSuperview];
                     }];
 
}

- (void)onClickImage:(UIGestureRecognizer *)gestureRecognizer {
    
    if (self.delegate != nil) {
        [self.delegate onClickCell:self ctrl:nil];
    }
}

- (void)updateCell:(Feed *)feed delegate:(id<ClickCellDelegate>)delegate {
    
    self.delegate = delegate;
    
    // Clear all the sub views
    for (UIView* subView in [self.contentView subviews]) {
        [subView removeFromSuperview];
    }
    
    CGRect frame;
    
    // Avatar
    frame.origin.x      = 10;
    frame.origin.y      = 8;
    frame.size.width    = 35;
    frame.size.height   = 35;
    UIImageView* avatarImageView = [[UIImageView alloc] initWithFrame:frame];
    self.avatarImageView = avatarImageView;
    [avatarImageView release];
    self.avatarImageView.image = feed.avatar;
    
    // Nickname
    frame.origin.x      = self.avatarImageView.frame.origin.x + self.avatarImageView.frame.size.width + 10;
    frame.origin.y      = self.avatarImageView.frame.origin.y;
    frame.size.width    = 320 - XEDGEMARGIN - self.avatarImageView.frame.size.width - 8 - XEDGEMARGIN;
    frame.size.height   = 16;
    UILabel* nicknameLabel = [[UILabel alloc] initWithFrame:frame];
    nicknameLabel.backgroundColor = [UIColor clearColor];
    nicknameLabel.textColor     = [UIColor colorWithRed:0x33 / 255.0 green:0x33 / 255.0 blue:0x33 / 255.0 alpha:1];
    nicknameLabel.font          = [UIFont fontWithName:@"Thonburi-Bold" size:16.0f];//[UIFont boldSystemFontOfSize:16.0f];
    nicknameLabel.textAlignment = UITextAlignmentLeft;
    nicknameLabel.text          = feed.nickname;
    self.nicknameLabel = nicknameLabel;
    [nicknameLabel release];
    
    // Favourite
    frame.origin.x      = 320 - 36;
    frame.origin.y      = 0;
    frame.size.width    = 36;
    frame.size.height   = 36;
    UIButton* favouriteMark = [[UIButton alloc] initWithFrame:frame];
    favouriteMark.backgroundColor = [UIColor clearColor];
    [favouriteMark setImage:[UIImage imageNamed:@"ico_heart_off"] forState:UIControlStateNormal];
    [favouriteMark setImage:[UIImage imageNamed:@"ico_heart_on"] forState:UIControlStateSelected];
    [favouriteMark addTarget:self action:@selector(onClickFavouriteMask:) forControlEvents:UIControlEventTouchUpInside];
    self.favouriteButton = favouriteMark;
    [favouriteMark release];
    
    // Timestamp
    UILabel* tsLabel = [[UILabel alloc] init];
    tsLabel.backgroundColor = [UIColor clearColor];
    tsLabel.textColor       = [UIColor colorWithRed:0xbb / 255.0 green:0xbb / 255.0 blue:0xbb / 255.0 alpha:1];
    tsLabel.font            = [UIFont fontWithName:@"Thonburi" size:11.0f];
    tsLabel.textAlignment   = UITextAlignmentLeft;
    tsLabel.text            = [Utility transTimeToCurrentFormat:feed.publishTime];
    //    [nicknameLabel sizeToFit];
    const int TSWidth = 80;
    frame.origin.x      = self.nicknameLabel.frame.origin.x;
    frame.origin.y      = self.nicknameLabel.frame.origin.y + self.nicknameLabel.frame.size.height + 6;
    frame.size.width    = TSWidth;
    frame.size.height   = 12;//self.avatarImageView.frame.size.height - 4 - 4 - self.nicknameLabel.frame.size.height;
    tsLabel.frame = frame;
    self.timestampLabel = tsLabel;
    [tsLabel release];
    
    // Note
    frame.size.width = 320 - 10 - 35 - 10 - 15;
    UILabel* noteLabel = [[UILabel alloc] initWithFrame:frame];
    noteLabel.backgroundColor   = [UIColor clearColor];
    noteLabel.textColor         = [UIColor blackColor];
    noteLabel.font              = [UIFont fontWithName:@"Thonburi" size:15.0f];//[UIFont systemFontOfSize:15.0f];
    noteLabel.textAlignment     = UITextAlignmentLeft;
    noteLabel.lineBreakMode     = UILineBreakModeWordWrap;
    noteLabel.numberOfLines     = 0;
    noteLabel.text              = feed.text;
    
    if (feed.text == nil || [feed.text isEqualToString:@""]) {
        frame = CGRectMake(self.timestampLabel.frame.origin.x, self.timestampLabel.frame.origin.y + self.timestampLabel.frame.size.height + YCTRLMARGIN, 0, 0);
        noteLabel.frame = frame;
    }
    else {
        [noteLabel sizeToFit];
        frame = noteLabel.frame;
        frame.origin.x  = self.timestampLabel.frame.origin.x;
        frame.origin.y  = self.avatarImageView.frame.origin.y + self.avatarImageView.frame.size.height;
        noteLabel.frame = frame;
    }
    self.noteLabel = noteLabel;
    [noteLabel release];
    
    // Image area
    if (feed.pictures != nil && [feed.pictures count] > 0) {
        
        frame.origin.x  = self.noteLabel.frame.origin.x;
        frame.origin.y  = self.noteLabel.frame.origin.y + self.noteLabel.frame.size.height + 8;
        UIImage* img = [UIImage imageNamed:[feed.pictures objectAtIndex:0]];
        CGSize picSize = img.size;
        frame.size.width = 160;
        frame.size.height = picSize.height * 160 / picSize.width;
        //    frame.size = [Utility properSizeForDisplay:feed.pictures];
        UIView* imageAreaView = [[UIView alloc] initWithFrame:frame];
        
        // Pictures
        CGRect picFrame = CGRectMake(0, 0, frame.size.width, frame.size.height);
        UIImageView* pictureView = [[UIImageView alloc] initWithFrame:picFrame];
        pictureView.image = img;
        
        // Number hint
        frame.size.width    = 30;
        frame.size.height   = 30;
        frame.origin.x      = imageAreaView.frame.size.width - frame.size.width;
        frame.origin.y      = imageAreaView.frame.size.height - frame.size.height;
        
        UIImage* picCountImage = [UIImage imageNamed:@"pic_count"];
        UIImageView* numberHintBg = [[UIImageView alloc] initWithImage:picCountImage];
        numberHintBg.frame = CGRectMake(imageAreaView.frame.size.width - picCountImage.size.width, imageAreaView.frame.size.height - picCountImage.size.height, picCountImage.size.width, picCountImage.size.height);
        
        CGRect hintLabelFrame = CGRectMake(imageAreaView.frame.size.width - frame.size.width * 2 / 3, imageAreaView.frame.size.height - frame.size.height * 2 / 3, frame.size.width * 2 / 3, frame.size.height * 2 / 3);
        UILabel* numberHint = [[UILabel alloc] initWithFrame:hintLabelFrame];
        numberHint.textColor = [UIColor whiteColor];
        numberHint.backgroundColor  = [UIColor clearColor];
        numberHint.font     = [UIFont systemFontOfSize:9.0f];
        numberHint.textAlignment = UITextAlignmentCenter;
        numberHint.text = [NSString stringWithFormat:@"%d张", [feed.pictures count]];
        
        [imageAreaView addSubview:pictureView];
        [imageAreaView addSubview:numberHintBg];
        [imageAreaView addSubview:numberHint];
        [pictureView release];
        [numberHintBg release];
        [numberHint release];
        self.imageAreaView = imageAreaView;
        
        UITapGestureRecognizer* tapGestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(onClickImage:)];
        [self.imageAreaView addGestureRecognizer:tapGestureRecognizer];
        [tapGestureRecognizer release];
        
        [imageAreaView release];
    }
    else {
        self.imageAreaView = nil;
    }
    
    // Original area
    if (feed.originalFeed != nil) {
        // Text
        UILabel* textArea = nil;
        frame = CGRectMake(15, 0, 260 - 30, 0);
        textArea = [[UILabel alloc] initWithFrame:frame];
        textArea.textColor      = [UIColor colorWithRed:0x21 / 255.0 green:0x1c / 255.0 blue:0x15 / 255.0 alpha:1];
        textArea.backgroundColor= [UIColor clearColor];
        textArea.font           = [UIFont fontWithName:@"Thonburi" size:15.0f];//[UIFont systemFontOfSize:14.0f];
        textArea.textAlignment  = UITextAlignmentLeft;
        textArea.lineBreakMode  = UILineBreakModeWordWrap;
        textArea.numberOfLines  = 0;
        textArea.text           = [NSString stringWithFormat:@"%@:%@", feed.originalFeed.nickname, feed.originalFeed.text];
        [textArea sizeToFit];
        frame = textArea.frame;
        frame.origin.x  = 15;
        frame.origin.y  = 15;
        textArea.frame = frame;
        
        // Image area
        UIView* imageAreaView = nil;
        if (feed.originalFeed.pictures != nil && [feed.originalFeed.pictures count] > 0) {
            frame.origin.x      = 15;
            frame.origin.y      = 15 + textArea.frame.size.height + 8;
            UIImage* img = [UIImage imageNamed:[feed.originalFeed.pictures objectAtIndex:0]];
            CGSize picSize = img.size;
            frame.size.width    = 160;
            frame.size.height   = picSize.height * 160 / picSize.width;
            imageAreaView = [[UIView alloc] initWithFrame:frame];
            
            // Pictures
            CGRect picFrame = CGRectMake(0, 0, frame.size.width, frame.size.height);
            UIImageView* OriginalPictureView = [[UIImageView alloc] initWithFrame:picFrame];
            OriginalPictureView.image = img;
            
            // Number hint
            frame.size.width    = 30;
            frame.size.height   = 30;
            frame.origin.x      = imageAreaView.frame.size.width - frame.size.width;
            frame.origin.y      = imageAreaView.frame.size.height - frame.size.height;
            
            UIImage* picCountImage = [UIImage imageNamed:@"pic_count"];
            UIImageView* numberHintBg = [[UIImageView alloc] initWithImage:picCountImage];
            numberHintBg.frame = CGRectMake(imageAreaView.frame.size.width - picCountImage.size.width, imageAreaView.frame.size.height - picCountImage.size.height, picCountImage.size.width, picCountImage.size.height);
            
            CGRect hintLabelFrame1 = CGRectMake(imageAreaView.frame.size.width - frame.size.width * 2 / 3, imageAreaView.frame.size.height - frame.size.height * 2 / 3, frame.size.width * 2 / 3, frame.size.height * 2 / 3);
            UILabel* numberHint = [[UILabel alloc] initWithFrame:hintLabelFrame1];
            numberHint.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"pic_count"]];
            numberHint.textColor = [UIColor whiteColor];
            numberHint.backgroundColor  = [UIColor clearColor];
            numberHint.font     = [UIFont systemFontOfSize:9.0f];
            numberHint.textAlignment = UITextAlignmentCenter;
            numberHint.text = [NSString stringWithFormat:@"%d张", [feed.originalFeed.pictures count]];
            
            [imageAreaView addSubview:OriginalPictureView];
            [imageAreaView addSubview:numberHintBg];
            [imageAreaView addSubview:numberHint];
            [OriginalPictureView release];
            [numberHintBg release];
            [numberHint release];
            
            UITapGestureRecognizer* tapGestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(onClickImage:)];
            [imageAreaView addGestureRecognizer:tapGestureRecognizer];
            [tapGestureRecognizer release];
        }
        
        frame.origin.x  = self.nicknameLabel.frame.origin.x;
        frame.origin.y  = self.noteLabel.frame.origin.y + self.noteLabel.frame.size.height;
        frame.size.width    = 260;//320 - 2 * XEDGEMARGIN - self.avatarImageView.frame.size.width - XCTRLMARGIN;
        frame.size.height   = 5 + textArea.frame.size.height + 8 + imageAreaView.frame.size.height + 20;
        UIView* originalAreaView = [[UIView alloc] initWithFrame:frame];
        originalAreaView.backgroundColor = [UIColor clearColor];//[UIColor colorWithRed:245.0 / 255.0 green:246.0 / 255.0 blue:251.0 / 255.0 alpha:1];
        if (textArea != nil) {
            [originalAreaView addSubview:textArea];
            [textArea release];
        }
        if (imageAreaView != nil) {
            [originalAreaView addSubview:imageAreaView];
            [imageAreaView release];
        }
        
        UIImage* sourceBgImg = [[UIImage imageNamed:@"forward_bg"] stretchableImageWithLeftCapWidth:0 topCapHeight:15];
        
        UIImageView* srcBgView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, originalAreaView.frame.size.width, originalAreaView.frame.size.height)];
        srcBgView.image = sourceBgImg;
        
        [originalAreaView insertSubview:srcBgView belowSubview:textArea];
        [srcBgView release];
        
        self.sourceAreaView = originalAreaView;
        [originalAreaView release];
    }
    else {
        self.sourceAreaView = nil;
    }
    
    // Description area
    frame.origin.x      = self.nicknameLabel.frame.origin.x;
    if (self.sourceAreaView != nil) {
        frame.origin.y  = self.sourceAreaView.frame.origin.y + self.sourceAreaView.frame.size.height + 8;
    }
    else if (self.imageAreaView != nil) {
        frame.origin.y  = self.imageAreaView.frame.origin.y + self.imageAreaView.frame.size.height + 8;
    }
    else if (self.noteLabel != nil) {
        frame.origin.y  = self.noteLabel.frame.origin.y + self.noteLabel.frame.size.height + 8;
    }
    frame.size.width    = 320 - 10 - 35 - 10 - 8;
    frame.size.height   = 12;
    UIView* descAreaView = [[UIView alloc] initWithFrame:frame];
    
    // Forward and comment Count show
    int commentCount, forwardCount;
    if (feed.originalFeed != nil) {
        commentCount = feed.originalFeed.commentNum;
        forwardCount = feed.originalFeed.forwardNum;
    }
    else {
        commentCount = feed.commentNum;
        forwardCount = feed.forwardNum;
    }
    // Forward count show
    frame.origin.x      = descAreaView.frame.size.width - 24;
    frame.origin.y      = 3;
    frame.size.width    = 24;
    frame.size.height   = descAreaView.frame.size.height;
    UILabel* forwardCountLabel = [[UILabel alloc] initWithFrame:frame];
    forwardCountLabel.textColor = [UIColor colorWithRed:0xbb / 255.0 green:0xbb / 255.0 blue:0xbb / 255.0 alpha:1];
    forwardCountLabel.backgroundColor   = [UIColor clearColor];
    forwardCountLabel.font  = [UIFont systemFontOfSize:12.0f];
    forwardCountLabel.textAlignment = UITextAlignmentLeft;
    forwardCountLabel.text  = [NSString stringWithFormat:@"%d", forwardCount];
    
    frame.origin.x      = forwardCountLabel.frame.origin.x - 12 - 2;
    frame.origin.y      = 2;
    frame.size.width    = 12;
    frame.size.height   = 12;
    UIImageView* forwardIndicator = [[UIImageView alloc] initWithFrame:frame];
    forwardIndicator.image = [UIImage imageNamed:@"ico_forward"];
    
    // Comment count show
    frame.origin.x      = forwardIndicator.frame.origin.x - 24;
    frame.origin.y      = 3;
    frame.size.width    = 24;
    frame.size.height   = descAreaView.frame.size.height;
    UILabel* commentCountLabel = [[UILabel alloc] initWithFrame:frame];
    commentCountLabel.textColor = [UIColor colorWithRed:0xbb / 255.0 green:0xbb / 255.0 blue:0xbb / 255.0 alpha:1];
    commentCountLabel.backgroundColor   = [UIColor clearColor];
    commentCountLabel.font  = [UIFont systemFontOfSize:12.0f];
    commentCountLabel.textAlignment = UITextAlignmentLeft;
    commentCountLabel.text  = [NSString stringWithFormat:@"%d", commentCount];
    
    frame.origin.x      = commentCountLabel.frame.origin.x - 12 - 2;
    frame.origin.y      = 2;
    frame.size.width    = 12;
    frame.size.height   = 12;
    UIImageView* commentIndicator = [[UIImageView alloc] initWithFrame:frame];
    commentIndicator.image = [UIImage imageNamed:@"ico_re"];
    
    // Tag area
    frame.origin.x  = 0;
    frame.origin.y  = 2;
    frame.size.width    = 12;
    frame.size.height   = 12;//descAreaView.frame.size.height;
    UIImageView* tagIndicator = [[UIImageView alloc] initWithFrame:frame];
    tagIndicator.image  = [UIImage imageNamed:@"ico_tag"];
    
    UILabel* tagContent = nil;
    if ((feed.tags != nil && [feed.tags count] > 0) ||
        (feed.originalFeed.tags != nil && [feed.originalFeed.tags count] > 0)) {
        frame.origin.x      = tagIndicator.frame.origin.x + tagIndicator.frame.size.width + 2;
        frame.origin.y      = 2;
        frame.size.width    = commentIndicator.frame.origin.x - tagIndicator.frame.origin.x - tagIndicator.frame.size.width - 4;
        frame.size.height   = descAreaView.frame.size.height;
        tagContent = [[UILabel alloc] initWithFrame:frame];
        tagContent.textColor    = [UIColor colorWithRed:0xbb / 255.0 green:0xbb / 255.0 blue:0xbb / 255.0 alpha:1];
        tagContent.font         = [UIFont systemFontOfSize:12.0f];
        tagContent.backgroundColor  = [UIColor clearColor];
        
        NSString* tagStr = @"";
        NSArray* tagArray = nil;
        if (feed.tags != nil) {
            tagArray = feed.tags;
        }
        else {
            tagArray = feed.originalFeed.tags;
        }
        for (NSString* str in tagArray) {
            tagStr = [tagStr stringByAppendingFormat:@"%@  ", str];
        }
        tagContent.text  = tagStr;
    }
    
    [descAreaView addSubview:tagIndicator];
    [tagIndicator release];
    if (tagContent != nil) {
        [descAreaView addSubview:tagContent];
        [tagContent release];
    }
    
    [descAreaView addSubview:forwardCountLabel];
    [forwardCountLabel release];
    [descAreaView addSubview:forwardIndicator];
    [forwardIndicator release];
    [descAreaView addSubview:commentCountLabel];
    [commentCountLabel release];
    [descAreaView addSubview:commentIndicator];
    [commentIndicator release];
    descAreaView.backgroundColor = [UIColor clearColor];
        
    // Add all the sub views
    [self.contentView addSubview:self.avatarImageView];
    //    [self.avatarImageView release];
    [self.contentView addSubview:self.nicknameLabel];
    
    [self.contentView addSubview:self.favouriteButton];
    // [self.nicknameLabel release];
    [self.contentView addSubview:self.timestampLabel];
    //[self.timestampLabel release];
    [self.contentView addSubview:self.noteLabel];
    //[self.noteLabel release];
    if (self.imageAreaView != nil) {
        [self.contentView addSubview:self.imageAreaView];
        //  [self.imageAreaView release];
    }
    if (self.sourceAreaView != nil) {
        [self.contentView addSubview:self.sourceAreaView];
        // [self.sourceAreaView release];
    }
    [self.contentView addSubview:descAreaView];
    
    frame = self.frame;
    CGFloat height = 8 + self.nicknameLabel.frame.size.height + 4 + self.timestampLabel.frame.size.height + 4;
    if (self.noteLabel != nil) {
        height += self.noteLabel.frame.size.height + 8;
    }
    if (self.imageAreaView != nil) {
        height += self.imageAreaView.frame.size.height + 8;
    }
    if (self.sourceAreaView != nil) {
        height += self.sourceAreaView.frame.size.height + 8;
    }
    height += self.descAreaView.frame.size.height + 8;
    
    if (self.sourceAreaView != nil) {
        height += 8;
    }
    else {
        height += 16;
    }

    frame.size.height = height;
    
    self.frame = frame;
}


@end
